use std::collections::HashSet;

static _SIMPLE_ASCII_CHARS: &str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
static _FULL_ASCII_CHARS: &str =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\\\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";

pub fn generate_ascii_image(
    filename: &str,
    ascii_chars: String,
    custom_size: u32,
) -> Result<String, image::ImageError> {
    let mut char_set: HashSet<char> = HashSet::new();
    let mut result = String::new();
    for c in ascii_chars.chars() {
        if !char_set.contains(&c) {
            char_set.insert(c);
            result.push(c);
        }
    }
    // let ascii_chars = char_set.into_iter().collect::<String>();
    let ascii_chars = result;

    let img = image::open(filename)?
        .thumbnail_exact(custom_size, custom_size)
        .to_luma8();

    let (width, height) = img.dimensions();
    let chars = ascii_chars;
    let char_step = 256.0 / chars.len() as f64;
    let mut output = String::with_capacity(width as usize * height as usize);
    for r in 0..height as usize {
        for c in 0..width as usize {
            let index = (img.get_pixel(c as u32, r as u32)[0] as f64 / char_step).floor() as usize;
            output.push(chars.chars().nth(index).unwrap());
            output.push(' ');
        }
        output.push('\n');
    }
    Ok(output)
}
